Popular Searches
Popular Course Categories
Popular Courses

Understanding Python Syntax and Indentation

Understanding Python Syntax and Indentation

Python Syntax, Variables, and Data Types

Understanding Python Syntax and Indentation

Course: Python Training Course

Topic: Understanding Python Syntax and Indentation

Course Link: Python Training Course at JustAcademy

Demo Registration: Register for a Free Course Demo

Website: Visit JustAcademy


1. Introduction to Python Syntax

Python syntax refers to the set of rules that determine how Python programs must be written so that the interpreter can understand and execute them. These rules cover statements, expressions, keywords, variables, operators, punctuation, quotation marks, and indentation.

Unlike natural languages, programming languages require precise structures. A missing colon, an unmatched parenthesis, or incorrect indentation can prevent a Python program from running.

Python is known for its readable syntax. It uses familiar English-like keywords and relies on indentation to define code blocks instead of requiring curly braces around every block.

Example: A Simple Python Program

name = "Aarav"
age = 22

print("Name:", name)
print("Age:", age)

Explanation:

  • name = "Aarav" assigns a string value to a variable.
  • age = 22 assigns an integer value to another variable.
  • print() displays information on the screen.
  • Each statement is written on a separate line for readability.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Understand the basic rules of Python syntax.
  • Identify Python statements, expressions, keywords, and identifiers.
  • Use colons, parentheses, quotation marks, and operators correctly.
  • Understand how indentation defines code blocks.
  • Write properly formatted conditional statements, loops, and functions.
  • Recognize and correct common syntax and indentation errors.
  • Apply Python naming and formatting conventions to improve code readability.

3. Understanding Python Statements

A statement is an instruction that Python can execute. Statements can assign values, display output, make decisions, repeat operations, or define functions and classes.

3.1 Assignment Statements

An assignment statement stores a value in a variable using the assignment operator (=).

city = "Mumbai"
temperature = 30
is_sunny = True

Here, three variables store a string, an integer, and a Boolean value.

3.2 Output Statements

The print() function displays text, values, or the results of expressions.

print("Welcome to Python")
print(10 + 20)
print("Total:", 150)

Output:

Welcome to Python
30
Total: 150

3.3 Conditional Statements

Conditional statements allow a program to execute different instructions depending on whether a condition is true or false.

marks = 75

if marks >= 40:
    print("Pass")
else:
    print("Fail")

The colon introduces each block, while indentation identifies the statements belonging to that block.

3.4 Loop Statements

Loops repeat instructions. Python supports for loops and while loops.

for number in range(1, 4):
    print(number)

Output:

1
2
3

4. Important Elements of Python Syntax

4.1 Keywords

Keywords are reserved words that have special meanings in Python. They form part of the language's grammar and cannot be used as ordinary variable or function names.

Examples include if, else, elif, for, while, def, return, class, try, except, import, and True.

if True:
    print("This condition is true")

In this example, if is a keyword and True is a Boolean constant. Neither should be used as a variable name.

4.2 Identifiers

An identifier is the name assigned to a variable, function, class, or another user-defined object.

student_name = "Priya"
total_marks = 450

def calculate_total():
    return total_marks

student_name, total_marks, and calculate_total are identifiers.

Rules for identifiers:

  • An identifier may contain letters, digits, and underscores.
  • It cannot begin with a digit.
  • It cannot contain spaces.
  • It cannot be a reserved Python keyword.
  • Identifiers are case-sensitive. For example, score and Score are different names.
Identifier Valid? Reason
student_name Yes Letters and underscore are allowed.
marks2 Yes Digits are allowed after the first character.
_total Yes An identifier can begin with an underscore.
2marks No An identifier cannot begin with a digit.
student name No Spaces are not allowed in identifiers.
class No class is a reserved keyword.

4.3 Literals

Literals are fixed values written directly in source code.

name = "Riya"       # String literal
age = 21            # Integer literal
price = 99.50       # Floating-point literal
is_active = True    # Boolean literal
result = None       # None literal

Python supports different literal types, including strings, integers, floating-point numbers, Boolean values, and collection literals such as lists, tuples, sets, and dictionaries.

4.4 Operators and Expressions

Operators perform operations on values. An expression combines values, variables, and operators to produce a result.

a = 10
b = 5

sum_value = a + b
difference = a - b
product = a * b
division = a / b

print(sum_value)
print(difference)
print(product)
print(division)

Python provides arithmetic, comparison, logical, assignment, membership, identity, and bitwise operators.

Operator Category Examples Purpose
Arithmetic + - * / // % ** Performs mathematical calculations.
Comparison == != > < >= <= Compares values and returns a Boolean result.
Logical and, or, not Combines or reverses logical conditions.
Assignment =, +=, -=, *= Assigns or updates variable values.
Membership in, not in Checks whether a value belongs to a collection.
Identity is, is not Checks whether two references point to the same object.

5. Understanding Python Indentation

Indentation means adding spaces or tabs at the beginning of a line. In Python, indentation is not merely a visual formatting choice. It defines the grouping of statements into code blocks.

Languages such as Java and JavaScript commonly use curly braces to group statements. Python normally uses a colon followed by an indented block.

5.1 Correct Indentation

age = 20

if age >= 18:
    print("You are an adult")
    print("You can apply for eligible services")

print("Program completed")

The two indented print() statements belong to the if block. The final statement is not indented, so it runs after the conditional block regardless of whether the condition is true.

5.2 Incorrect Indentation

age = 20

if age >= 18:
print("You are an adult")

This code produces an IndentationError because Python expects the body of the if statement to be indented.

Correct version:

age = 20

if age >= 18:
    print("You are an adult")

5.3 Recommended Indentation Size

Python's standard style guide, PEP 8, recommends using four spaces per indentation level. Consistent spaces make nested code easier to read and maintain.

def greet_user():
    name = "Aarav"

    if name:
        print("Hello,", name)

greet_user()

In this example:

  • The function body is indented four spaces.
  • The if body is indented eight spaces from the left margin.
  • The function call is at the top level because it is outside the function definition.

5.4 Spaces Versus Tabs

Python can encounter indentation problems when tabs and spaces are mixed inconsistently within a block. Prefer four spaces per indentation level and configure your code editor to insert spaces when you press Tab.

Many editors, including Visual Studio Code and PyCharm, provide indentation guides and automatic formatting tools to help maintain consistency.

6. Why Indentation Matters

  • Defines code blocks: Indentation determines which statements belong to conditions, loops, functions, classes, and exception handlers.
  • Improves readability: Properly aligned code makes program logic easier to understand.
  • Prevents errors: Correct indentation helps avoid syntax and indentation errors.
  • Clarifies program flow: Readers can quickly identify nested statements and the scope of each block.
  • Supports maintenance: Consistent formatting makes code easier to update, test, and review.

7. Indentation in Conditional Statements

Conditional statements use if, elif, and else. Each condition header ends with a colon, and its body must be indented.

marks = 82

if marks >= 90:
    print("Grade A+")
elif marks >= 75:
    print("Grade A")
elif marks >= 60:
    print("Grade B")
else:
    print("Needs improvement")

Python checks the conditions from top to bottom. The first condition that evaluates to true determines which block executes.

Common mistake: Indenting elif or else as though it were part of the previous block.

# Incorrect
if marks >= 90:
    print("Grade A+")
    else:
        print("Other grade")

Correct version:

if marks >= 90:
    print("Grade A+")
else:
    print("Other grade")

8. Indentation in Loops

Loops repeat a block of statements. All statements that should execute during each iteration must be indented consistently.

8.1 For Loop

for number in range(1, 6):
    square = number ** 2
    print(number, "squared is", square)

Both statements inside the loop execute for each value from 1 to 5.

8.2 While Loop

count = 1

while count <= 3:
    print("Count:", count)
    count += 1

print("Loop finished")

The counter update is indented inside the loop, so the condition eventually becomes false. If the update were omitted, the loop could continue indefinitely.

8.3 Nested Loops

A nested loop is a loop placed inside another loop. The inner loop requires another indentation level.

for row in range(1, 4):
    for column in range(1, 3):
        print("Row:", row, "Column:", column)
    print("End of row", row)

The inner print() executes during each inner-loop iteration. The final print() in the loop body executes once after the inner loop completes for each row.

9. Indentation in Functions

A function is a reusable block of code defined with the def keyword. The function body must be indented beneath the function header.

def calculate_area(length, width):
    area = length * width
    return area

result = calculate_area(10, 5)
print("Area:", result)

The variable calculation and return statement belong to the function. The function call is outside the definition and runs at the top level.

9.1 Functions with Multiple Blocks

def check_number(number):
    if number > 0:
        return "Positive"
    elif number < 0:
        return "Negative"
    else:
        return "Zero"

print(check_number(-4))

The function body uses one indentation level, and each conditional branch uses another. This structure helps Python distinguish the function's logic from the code outside it.

10. Indentation in Classes

Classes define the structure and behavior of objects. Statements inside a class definition are indented under the class header, and method bodies are indented one additional level.

class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def display(self):
        print("Name:", self.name)
        print("Marks:", self.marks)

student = Student("Riya", 88)
student.display()

The constructor and the display() method are members of the class. The statements inside each method belong to that method's body.

11. Colons and Code Blocks

A colon (:) is commonly used after statements that introduce an indented block. It tells Python that a suite of statements follows.

Common examples include:

  • if condition:
  • elif condition:
  • else:
  • for item in collection:
  • while condition:
  • def function_name():
  • class ClassName:
  • try:, except:, finally:
  • with resource:

Example:

try:
    value = int("123")
    print(value)
except ValueError:
    print("Invalid integer")

Forgetting the colon after a block header usually produces a SyntaxError.

12. Line Breaks and Multiple Statements

Python generally treats a newline as the end of a statement. This makes simple programs easy to read without adding a semicolon to every line.

first_name = "Aarav"
last_name = "Shah"
full_name = first_name + " " + last_name

print(full_name)

Although Python allows multiple simple statements on one line separated by semicolons, placing one statement per line is usually easier to read.

# Valid, but less readable
x = 10; y = 20; print(x + y)

# Recommended
x = 10
y = 20
print(x + y)

12.1 Implicit Line Continuation

Long expressions can be split across multiple lines inside parentheses, brackets, or braces. This is called implicit line continuation.

total = (
    100
    + 200
    + 300
)

print(total)

Lists and function calls can also span multiple lines:

student_names = [
    "Aarav",
    "Riya",
    "Kabir"
]

print(student_names)

For expressions outside brackets or parentheses, a backslash can explicitly continue a line, but using parentheses is generally clearer and less error-prone.

13. Comments and Docstrings

13.1 Single-Line Comments

A comment begins with the # character. Python ignores the comment text when executing the program.

# Calculate the total price
price = 250
quantity = 3
total = price * quantity

print(total)

13.2 Indentation of Comments

Comments should generally align with the code they explain. A comment inside a function or loop is indented to match its logical position.

def calculate_discount(price):
    # Apply a 10% discount
    discount = price * 0.10
    return price - discount

13.3 Docstrings

A docstring is a string literal placed at the beginning of a module, function, class, or method to describe its purpose.

def greet(name):
    """Return a greeting for the supplied name."""
    return f"Hello, {name}!"

print(greet("Riya"))

Unlike ordinary comments, docstrings can be accessed through documentation tools and attributes such as greet.__doc__.

14. Python Syntax Versus Indentation

Feature Syntax Indentation
Meaning The rules governing valid Python code. The leading whitespace used to structure code blocks.
Examples Keywords, expressions, parentheses, colons. Four spaces before statements in a block.
Purpose Ensures instructions follow Python's grammar. Identifies which statements belong together.
Common error SyntaxError IndentationError or TabError
Example correction Add a missing colon or closing parenthesis. Align block statements consistently.

15. Common Syntax and Indentation Errors

15.1 Missing Colon

# Incorrect
if age >= 18
    print("Eligible")

Problem: The conditional header does not end with a colon.

# Correct
if age >= 18:
    print("Eligible")

15.2 Missing Indentation

# Incorrect
for item in items:
print(item)

Problem: The loop body is not indented.

# Correct
for item in items:
    print(item)

15.3 Unexpected Indentation

# Incorrect
name = "Riya"
    print(name)

Problem: The statement has unnecessary indentation at the top level.

# Correct
name = "Riya"
print(name)

15.4 Inconsistent Indentation

# Incorrect example
if True:
    print("First line")
      print("Second line")

Problem: The two statements intended to share a block use different indentation levels. Depending on the structure, Python may raise an indentation error or interpret the code differently than intended.

# Correct
if True:
    print("First line")
    print("Second line")

15.5 Unmatched Parentheses

# Incorrect
print("Hello"

# Correct
print("Hello")

Problem: The closing parenthesis is missing, so Python cannot parse the statement correctly.

15.6 Unclosed String

# Incorrect
message = "Welcome to Python

# Correct
message = "Welcome to Python"

Problem: The opening quotation mark does not have a matching closing quotation mark.

15.7 Incorrect Keyword Spelling or Capitalization

# Incorrect
If age >= 18:
    print("Adult")

# Correct
if age >= 18:
    print("Adult")

Python keywords are case-sensitive. Writing If instead of if causes a syntax error.

16. Syntax Errors, Indentation Errors, and Runtime Errors

Error Type Meaning Example How to Fix
SyntaxError Python cannot parse the code because it violates language grammar. if x > 5 print(x) Check punctuation, keywords, brackets, and statement structure.
IndentationError Indentation is missing or structurally invalid. A block body is not indented. Align statements within the correct block.
TabError Tabs and spaces are used inconsistently in indentation. Mixing tabs and spaces in one block. Convert indentation to consistent spaces.
NameError A name is used before it has been defined in the current scope. print(total) when total is undefined. Define the variable or correct its spelling and scope.
TypeError An operation is applied to an incompatible type. "Age: " + 20 Convert the value to a suitable type or use formatted output.

Syntax and indentation problems are generally detected before the affected code can execute. Runtime errors occur during execution, while some logical errors allow a program to run but produce incorrect results.

17. Best Practices for Writing Clean Python Code

  • Use four spaces per indentation level, following PEP 8.
  • Keep indentation consistent throughout a file.
  • Use meaningful names such as total_price rather than unclear names such as tp.
  • Use lowercase words separated by underscores for ordinary variables and functions, as recommended by PEP 8.
  • Put a colon after block headers such as if, for, and def.
  • Keep related statements together and separate unrelated sections with blank lines where appropriate.
  • Use parentheses to split long expressions across lines.
  • Write comments that explain intent, decisions, or non-obvious logic.
  • Use a code editor with Python syntax highlighting and indentation guides.
  • Run programs regularly instead of waiting until a large amount of code has been written.
  • Read the complete error message and traceback to locate the relevant line.
  • Consider tools such as ruff, black, or autopep8 to help check or format code.

18. Using a Code Editor to Check Indentation

Most Python editors provide features that reduce formatting mistakes.

Recommended Workflow

  1. Open the Python file in an editor such as Visual Studio Code or PyCharm.
  2. Confirm that the file is recognized as Python code.
  3. Configure the editor to use spaces rather than tabs for indentation.
  4. Check that nested blocks align consistently.
  5. Use the editor's formatting or linting tools if available.
  6. Save the file with a .py extension.
  7. Run the program and review any reported errors.

Example Program

# File: syntax_practice.py

def check_even_or_odd(number):
    if number % 2 == 0:
        return "Even"
    else:
        return "Odd"

for value in range(1, 6):
    result = check_even_or_odd(value)
    print(value, "is", result)

This program demonstrates a function, a conditional statement, a loop, a return value, and multiple indentation levels.

19. Practical Example: Student Result Calculator

In this example, a program calculates the average of three marks and assigns a result category. It demonstrates how correct syntax and indentation make the program easier to follow.

# Student Result Calculator

student_name = input("Enter student name: ")

mark1 = float(input("Enter first mark: "))
mark2 = float(input("Enter second mark: "))
mark3 = float(input("Enter third mark: "))

average = (mark1 + mark2 + mark3) / 3

print("\nStudent:", student_name)
print("Average:", round(average, 2))

if average >= 75:
    print("Result: Distinction")
elif average >= 40:
    print("Result: Pass")
else:
    print("Result: Fail")

How the Program Works

  1. The program accepts a student's name.
  2. It accepts three marks and converts the input strings into floating-point numbers.
  3. It calculates the average using arithmetic operators.
  4. It displays the name and average.
  5. The conditional statements classify the result.
  6. The indentation identifies which output belongs to each condition.

Important improvement: This beginner example assumes that the user enters valid numbers and marks within the expected range. A production-ready version should validate input and reject marks outside the permitted range.

20. Practical Example: Correcting an Indentation Bug

Consider this program, where the total is displayed outside the loop:

numbers = [10, 20, 30]
total = 0

for number in numbers:
    total += number

print("Total:", total)

Output:

Total: 60

The loop adds every number to total. The final print statement is outside the loop, so the total is displayed only once after all numbers have been processed.

If the print statement were indented inside the loop, the program would display the running total during each iteration:

numbers = [10, 20, 30]
total = 0

for number in numbers:
    total += number
    print("Running total:", total)

Output:

Running total: 10
Running total: 30
Running total: 60

This illustrates that indentation can affect program behavior even when the code is syntactically valid.

21. Hands-On Exercises

Exercise 1: Basic Syntax

Create a Python program that stores your name, age, and city in variables and prints each value on a separate line.

Exercise 2: Correct the Missing Colon

Find and correct the error in the following code:

temperature = 35

if temperature > 30
    print("It is hot")

Exercise 3: Fix Indentation

Correct the indentation so that both messages appear only when the condition is true.

age = 19

if age >= 18:
print("Adult")
print("Eligible to apply")

Exercise 4: Write a Loop

Write a for loop that displays the numbers from 1 to 10 and their squares. Ensure both calculation and output statements are indented inside the loop.

Exercise 5: Create a Function

Write a function named calculate_discount(price) that calculates a 10% discount and returns the final price. Call the function and print its result.

Exercise 6: Identify the Error Type

For each example, identify whether the problem is a syntax error, indentation error, name error, or runtime type error.

# A
if True
    print("Hello")

# B
if True:
print("Hello")

# C
print(total_amount)  # Assume it was never defined.

# D
result = "Price: " + 100

22. Mini Project: Simple Billing System

Objective: Build a basic billing program that calculates the subtotal, discount, and final bill. The project reinforces variable assignments, expressions, conditional logic, and indentation.

# Simple Billing System

item_name = input("Enter item name: ")
price = float(input("Enter item price: "))
quantity = int(input("Enter quantity: "))

subtotal = price * quantity

if subtotal >= 1000:
    discount = subtotal * 0.10
else:
    discount = 0

final_amount = subtotal - discount

print("\n--- BILL SUMMARY ---")
print("Item:", item_name)
print("Price:", price)
print("Quantity:", quantity)
print("Subtotal:", round(subtotal, 2))
print("Discount:", round(discount, 2))
print("Final amount:", round(final_amount, 2))

Project Requirements

  • Accept an item name, price, and quantity.
  • Calculate the subtotal.
  • Apply a 10% discount when the subtotal is at least 1,000.
  • Display the complete bill summary.
  • Maintain consistent indentation in the conditional block.

Extension: Add input validation to ensure that the price is not negative and the quantity is a positive integer. You can also extend the program to calculate tax or process multiple items.

23. Interview Questions and Answers

Q1. What is Python syntax?

Answer: Python syntax is the set of rules that define how Python statements, expressions, and code blocks must be written so the interpreter can parse them.

Q2. Why is indentation important in Python?

Answer: Indentation defines the grouping of statements into blocks. It determines which statements belong to conditions, loops, functions, classes, and other compound statements.

Q3. How many spaces should be used for indentation?

Answer: PEP 8 recommends four spaces per indentation level.

Q4. What happens if indentation is incorrect?

Answer: Python may raise an IndentationError or TabError. In other cases, valid but unintended indentation may change program behavior.

Q5. What is the purpose of a colon in Python?

Answer: A colon introduces a suite or block after headers such as if, for, while, def, and class.

Q6. What is the difference between a statement and an expression?

Answer: A statement performs an instruction, such as assigning a value. An expression evaluates to a value, such as 5 + 3. Expressions can appear inside statements.

Q7. Are Python identifiers case-sensitive?

Answer: Yes. Names such as total, Total, and TOTAL are treated as different identifiers.

Q8. Can tabs and spaces be mixed in Python?

Answer: Mixing tabs and spaces inconsistently in indentation can cause a TabError or other indentation problems. Using four spaces consistently is recommended.

Q9. What is the difference between a SyntaxError and an IndentationError?

Answer: A SyntaxError indicates that code violates Python's grammar. An IndentationError is a specific type of syntax error related to incorrect indentation.

Q10. Does indentation affect the output of a program?

Answer: Yes. Indentation determines which statements execute inside a block. Moving a statement into or out of a loop or condition can change when and how often it runs.

Q11. What is PEP 8?

Answer: PEP 8 is the Python style guide that provides conventions for writing readable and consistent Python code, including indentation and naming practices.

Q12. How can beginners prevent indentation errors?

Answer: Use a Python-aware editor, configure four spaces per indentation level, avoid mixing tabs and spaces, check block alignment, and run the program frequently.

24. Quick Revision Checklist

  • Python syntax defines the rules for writing valid code.
  • Statements perform instructions, while expressions evaluate to values.
  • Keywords are reserved words with special meanings.
  • Identifiers are names for variables, functions, classes, and other objects.
  • Python uses colons to introduce many compound statement blocks.
  • Indentation defines the boundaries of code blocks.
  • Four spaces per indentation level are recommended by PEP 8.
  • Use consistent spaces instead of mixing tabs and spaces.
  • Indent statements correctly inside conditions, loops, functions, and classes.
  • Syntax errors and indentation errors should be corrected before the program can run successfully.
  • Correct indentation also helps ensure that a valid program behaves as intended.
  • Practice by writing small programs and deliberately correcting common errors.

25. Conclusion

Understanding Python syntax and indentation is a fundamental step toward writing reliable Python programs. Syntax determines how instructions must be written, while indentation identifies the relationships between statements and the blocks they belong to.

By learning the rules for identifiers, keywords, expressions, colons, line breaks, and indentation, beginners can prevent common errors and write programs that are easier to read, test, and maintain. Regular practice with conditions, loops, functions, and small projects will help make these rules part of everyday programming.

To continue learning Python, explore the Python Training Course at JustAcademy. You can also register for a course demo or visit the JustAcademy website for more learning opportunities.

whatsapp